//预支付订单（扫底+）
var basePage = require('../../../common/BasePage');
Page({
  behaviors: [basePage],
    data: {
        /**支付凭证 */
        pay_cert: {
            /**完整图片路径 */
            url: '/assets/photo.png',
            /**后台地址 */
            photo: '',
            /**''未选择;loading 上传中;error 上传失败;ok 上传成功 */
            state: '',
        },
         /**支付密码 */
         password: '',
        /**订单信息 */
        order: {},
        /**地址信息 */
        m_addr: null,
        /**选中的优惠券信息 */
        coupon:{cid:0},
        /**支付方式 */
        pay: 'wxpay',
        /**支付参数 */
        payData: {},
        /**是否显示密码输入框 */
        passPop: false,
        show: false,
       
        fileList: [],
        price: 0,
        allow_upload: false, //允许上传图片,radio===3时允许
        max_count: 2, //付款凭证图片可上传数量
        // coupon_radio: '', //优惠券选中项
        
        canSubmit:true,
        /**当前仓库 */
        warehouse:{},
        /**是否提示起购数量 */
        showNumTip:true
    },
    onLoad: function (option) {
        // console.log(option.query);
        option.noShowNum?this.data.showNumTip=false:'';
        let that = this;
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('orderData', function (data) {
            // console.log
            data.data.thumb= that.get_thumb(data.data.product_img);
            data.data.pdc_amount =  data.data.product_price *  data.data.nums;
           
            that.setData({
                m_addr: data.m_addr,
                order: data.data,
                warehouse:getApp().globalData.warehouse
            })
            if(data.data.coupon_list&&data.data.coupon_list.length){
                that.data.coupon=data.data.coupon_list[0]
            }
        })
    },
     /**设置支付密码 */
     edit_pass() {
        this.request({
            url: this.data.host + '/home/user/editPasswd',
            data: {
                password: this.data.repass
            },
            method: 'post'
        }, res => {
            wx.showToast({
                title: '设置成功',
                icon: 'none'
            });
            this.setData({
                editPassPop: false
            })
        });
    },
    /**
     * 确认订单（立即支付）
     */
    submit_order(){
        let that=this;
        if(!this.data.canSubmit){
            return wx.showToast({
              title: '请勿频繁提交',
              icon:'none'
            })
        }
        this.data.canSubmit=false;
        setTimeout(() => {
            this.data.canSubmit=true;
        }, 1000);
        let tip='此商品由'+this.data.warehouse.title+"派送，请确认";
        if(this.data.warehouse.wh_id==1&&this.data.showNumTip){
            tip='此商品由'+this.data.warehouse.title+"派送，需要30扎混搭发货，请确认";
        }
        wx.showModal({
          
          cancelText: '取消',
       
          confirmText: '确认',
          content:tip,
        
          showCancel: true,
          title: '提示',
          success: (result) => {
            if (result.confirm){
                that.req_submit()
            }
          },

        })
       
    },
    req_submit(){
        let order=this.data.order;
        let handleUrl='/home/ump/sweep/handle';
        if(order.seckill_id){
            handleUrl="/home/ump/seckill/handle";
        }else if(order.presell_id){
            handleUrl="/home/ump/presell/handle";
        }
        //请求购物车数据
        this.request({
            url: this.data.host +handleUrl,
            data:{
                presell_id:order.presell_id,
                seckill_id:order.seckill_id,
                sweep_id:order.sweep_id,
                addr_id:this.data.m_addr.addr_id,
                nums:this.data.order.nums,
                wh_id:getApp().globalData.warehouse.wh_id
            },
            method: 'post'
        }, this.submit_ok);
    },
    submit_ok(obj){
        console.log("submit_ok",obj);
        this.data.payData = {
            order_id: obj.data.order_id,
            code: this.data.pay
        }
        this.check_pay();
    
    },
    /**检查支付方式 */
    check_pay() {
        // if (this.data.pay == "money") { //密码支付，弹出密码输入框
        //     return this.setData({
        //         passPop: true
        //     })
        // }
        this.pay_order()
    },
    /**
     * 支付订单
     */
    pay_order() {
        // let that=this;
        this.data.pay_cert.photo?this.data.payData.pay_cert=this.data.pay_cert.photo:'';
        this.request({
            url: this.data.host + '/home/payment/order',
            method: "POST",
            data: this.data.payData
        }, res => {
            //  console.log("payment/order",res,this.data.payData.code);
            if (this.data.payData.code == 'wxpay') { //调用微信支付
                wx.requestPayment({
                    ...res.data.pay_data,
                    success(res) {
                        wx.showToast({
                            title: '支付成功',
                        })

                    },
                    fail(err) {
                        wx.showToast({
                            title: '支付失败',
                            icon: 'none'
                        })
                        console.error('pay fail', err)
                    },
                    complete() {
                        wx.redirectTo({
                            url: '/pages/cls/my_order/order',
                        })
                    }
                })
            } else {
                wx.redirectTo({
                    url: '/pages/cls/my_order/order',
                })
            }
            //  return;

        });
    },
    addr_click() {
        let that=this;
        wx.navigateTo({
            url: '/pages/addr/AddrList',
            events: {
                change_addr: function (data) {
                    console.log("change_addr", data);
                    that.setData({
                        m_addr: data.addr
                    })
                }
            }
        })
    },
    open_van_action_sheet() {
        this.setData({
            show: true
        });
    },
    onClose() {
        this.setData({
            show: false
        });
    },
    onSelect(event) {
        console.log(event.detail);
    },
    onClick(event) {
        let name = event.currentTarget.dataset.name;
        this.data.payData.code = name;
        this.setData({
            pay: name,
        })
    },
     /**
     * 凭证上传
     */
    img_upload(e) {
        let that = this;
        /**上传图片的对象 */
        let img = e.currentTarget.dataset.img;
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success(imgRes) {
                // tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = imgRes.tempFilePaths;
                console.log("tempFilePaths", tempFilePaths);
                let photo = {}; //用于更新视图诗句
                let id_photo_front = photo[img] = that.data[img];
                id_photo_front.url = tempFilePaths[0];
                id_photo_front.state = "loading";
                console.log("photo", photo)
                that.setData(photo)
                wx.uploadFile({
                    filePath: tempFilePaths[0],
                    name: 'image',
                    url: that.data.host + '/home/upload/image',
                    formData: {
                        from: 'verify'
                    },
                    success(res) {
                        id_photo_front.state = "error";
                        // id_photo_front.photo='';
                        // console.log("home/upload/image", res);
                        if (res.statusCode != 200) {
                            return wx.showModal({
                                showCancel: false,
                                content: res.errMsg || '上传失败',
                            })
                        }
                        let resObj = JSON.parse(res.data);
                        if (resObj.code) {
                            return wx.showToast({
                                title: resObj.msg,
                                icon: 'none'
                            })
                        }
                        id_photo_front.state = "ok";
                        id_photo_front.photo = resObj.data.path;

                    },
                    fail() {
                        id_photo_front.state = "error";
                        wx.showModal({
                            showCancel: false,
                            content: '上传接口异常',
                        })
                    },
                    complete() {
                        that.setData(photo)
                    }
                });
            },
            fail(e) {
                wx.showToast({
                    title: e.errMsg || '调用微信文件失败',
                    icon: 'none'
                })
                // console.log(e);
            }
        })
    },
    // clickUpload() {
    //     if (parseInt(this.data.radio) !== 3) {
    //         wx.showToast({
    //             title: '仅线下支付允许上传凭证',
    //             icon: 'none'
    //         })
    //     }
    // },
    // radioChange(e) {
    //     console.log("radioChange",e)
    //     this.setData({
    //         coupon_radio: e.detail,
    //         show: false
    //     })
    // },
    afterRead(event) {
        const {
            file
        } = event.detail;
        let {
            fileList = []
        } = this.data;
        file.forEach(item => {
            fileList.push(item);
        })
        this.setData({
            fileList
        });
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        // wx.uploadFile({
        //     url: 'https://example.weixin.qq.com/upload',
        //     filePath: file.url,
        //     name: 'file',
        //     formData: { user: 'test' },
        //     success(res) {
        //         // 上传完成需要更新 fileList
        //         const { fileList = [] } = this.data;
        //         fileList.push({ ...file, url: res.data });
        //         this.setData({ fileList });
        //     },
        // });
    },
    submit_pass() {
        if (!this.data.password) {
            return wx.showToast({
                title: '请先输入密码',
                icon: 'none'
            })
        }
        this.setData({
            passPop: false
        })
        this.data.payData.password = this.data.password;
        this.pay_order()
        // console.log("password",this.data.password);
        // console.log("payData",this.data.payData);
    },
    /**显示密码重置弹窗 */
    show_edit() {
        this.setData({
            editPassPop: true
        })
    }
    // delete_image(e) {
    //     let {
    //         fileList = []
    //     } = this.data;
    //     fileList.splice(e.detail.index, 1);
    //     this.setData({
    //         fileList
    //     });
    // },
})